import React, { Component, Fragment } from 'react';
import axios from 'axios';
import './style.css';
import TodoItem from './TodoItem';
class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      list: ['学英语', 'Learning react']
    }
    this.handleItemDelete = this.handleItemDelete.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handBtnClick = this.handBtnClick.bind(this);
  }

  componentWillMount(){

  }
  
  componentDidMount(){
    //ajax请求获取数据
    axios.get('/api/todolist')
    .then((response)=>{
      this.setState(()=>({
        list:[...response.data]
      }))
    })
    .catch((error)=>{
      console.log(error);
    });
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            type="text"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
            ref={(input) => { this.input = input }}
          />
          <button onClick={this.handBtnClick}>提交</button>
        </div>
        {/* 列表渲染 */}
        <ul>
          {this.getTodoItem()}
        </ul>
      </Fragment>
    )
  }
  //获取列表
  getTodoItem() {
    return this.state.list.map((item, index) => {
      return (
        <TodoItem
          key={index}
          content={item}
          index={index}
          onItemDelete={this.handleItemDelete}
        />
      )
    })
  }
  //input实时更改数值
  handleInputChange(e) {
    const value = e.target.value;
    this.setState(() => ({  //setState是一个异步函数，变化是缓慢的，想要立即获得改变的值，需要放在setState的回调函数中
      inputValue: value
    }),
      () => { //setState的回调函数
        console.log(this.input.value)
      })
  }
  //输入数据
  handBtnClick() {
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: '',
    }))
  }
  //删除数据
  handleItemDelete(index) {
    this.setState((prevState) => {//不建议使用，react不允许我们队state做任何的改变
      const list = [...prevState.list];
      list.splice(index, 1)
      return { list }
    })
  }
}

export default TodoList